<template>
  <!-- 加载状态 -->
  <div v-if="loading" class="loading-state">
    <div class="content">
      <div class="searchB_hp">
        <el-icon class="search-icon"><Search /></el-icon>
        <el-date-picker 
          v-model="date" 
          type="month" 
          placeholder="选择月份"
          format="YYYY-MM"
          value-format="YYYY-MM"
          @change="bindDateChange"
          class="date-picker"
          size="small"
          disabled
        />
      </div>
      <div class="echatu">
        <div class="loading-wrapper">
          <el-skeleton :rows="3" animated />
        </div>
      </div>
    </div>
  </div>
  
  <!-- 有数据时显示 -->
  <div v-else-if="objlist.leixing === 'ok'" class="content">
    <!-- 搜索栏 - 按照uni-app风格 -->
    <div class="searchB_hp">
      <el-icon class="search-icon"><Search /></el-icon>
      <el-date-picker 
        v-model="date" 
        type="month" 
        placeholder="选择月份"
        format="YYYY-MM"
        value-format="YYYY-MM"
        @change="bindDateChange"
        class="date-picker"
        size="small"
      />
      <!-- 调试按钮 -->
      <el-button size="small" @click="getData_index" style="margin-left: 10px;">刷新</el-button>
    </div>
    
    <!-- 图表区域 -->
    <div class="echatu" v-if="objlist.obj">
      <div ref="chartRef" :style="{ width: chartwidth + 'px', height: chartheight + 'px' }"></div>
    </div>
  </div>
  
  <!-- 空状态/错误状态 -->
  <div v-else class="empty-state">
    <div class="content">
      <div class="searchB_hp">
        <el-icon class="search-icon"><Search /></el-icon>
        <el-date-picker 
          v-model="date" 
          type="month" 
          placeholder="选择月份"
          format="YYYY-MM"
          value-format="YYYY-MM"
          @change="bindDateChange"
          class="date-picker"
          size="small"
        />
        <!-- 调试按钮 -->
        <el-button size="small" @click="getData_index" style="margin-left: 10px;">获取数据</el-button>
      </div>
      <div class="echatu">
        <el-empty description="暂无数据，请尝试重新查询" />
      </div>
    </div>
  </div>
</template>

<script>
import { ref, onMounted, nextTick, onUnmounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { Search } from '@element-plus/icons-vue'
import request, { getApiPath } from '@/utils/request'
import { Base64 } from 'js-base64'
import * as echarts from 'echarts'

export default {
  name: 'Tjtb',
  components: {
    Search
  },
  setup() {
    const route = useRoute()
    
    // 响应式数据 - 完全按照uni-app的data结构
    const loading = ref(false) // 先设为false，让界面正常显示
    const chartRef = ref(null)
    const objlist = ref({
      leixing: '', // 初始状态
      obj: null
    })
    const option = ref({})
    const dtype = ref('')
    const chartheight = ref(0)
    const chartwidth = ref(0)
    
    // 从路由参数中获取 dtype - 模拟uni-app的onLoad方法
    const initializeFromRoute = () => {
      console.log('初始化页面参数 - route.query:', route.query)
      
      // 检查路由参数中是否有 type 参数
      if (route.query.type) {
        dtype.value = route.query.type
        console.log('从路由参数获取 dtype:', dtype.value)
      } else if (route.query.dtype) {
        dtype.value = route.query.dtype
        console.log('从路由参数获取 dtype (备用):', dtype.value)
      } else {
        // 默认值 - 可以根据需要设置
        dtype.value = 'yue_meirizjt'
        console.log('使用默认 dtype:', dtype.value)
      }
    }
    
    // 当前日期 - 按照uni-app的getDate方法
    const getDate = (type) => {
      const date = new Date()
      let year = date.getFullYear()
      let month = date.getMonth() + 1
      
      if (type === 'start') {
        year = year - 10
      } else if (type === 'end') {
        year = year + 10
      }
      month = month > 9 ? month : '0' + month
      return `${year}-${month}`
    }
    
    const date = ref(getDate({ format: true }))
    let chartInstance = null
    
    // 更新屏幕尺寸 - 按照uni-app的updateScreenWidth方法
    const updateScreenWidth = () => {
      const windowHeight = window.innerHeight
      const windowWidth = window.innerWidth
      
      // 适配web端显示
      chartheight.value = Math.max(windowHeight - 120, 400) // 最小高度400px
      chartwidth.value = Math.max(windowWidth - 40, 800) // 最小宽度800px，考虑左右边距
      
      console.log('uniapp风格 屏幕尺寸更新:', { 
        height: chartheight.value, 
        width: chartwidth.value,
        windowHeight,
        windowWidth
      })
      
      // 如果图表已经初始化，重新调整大小
      if (chartInstance) {
        setTimeout(() => {
          chartInstance.resize()
        }, 100)
      }
    }
    
    // 完全按照uni-app的getData_index方法
    const getData_index = async () => {
      loading.value = true
      try {
        console.log('uniapp风格 开始获取统计数据')
        
        // 完全按照uni-app的参数结构
        const bs64_cs = {
          dtype: dtype.value,
          yue: date.value
        }
        
        const cs = {
          ctype: 'zlxt_tongjibaobiao',
          bs64_cs: Base64.encode(JSON.stringify(bs64_cs)),
          bs64_obj: '',
          bs64_list: '',
          bs64_obj_zhub: '',
          ids: '',
          faid: 0
        }
        
        // console.log('uniapp风格 统计请求参数:', bs64_cs)
        // console.log('uniapp风格 统计API请求:', cs)
        
        const res = await request.post(getApiPath(cs.ctype), { canshu: cs })
        console.log('uniapp风格 统计API响应:', res)
        
        if (res && res.leixing === 'ok') {
          // 设置页面标题 - 按照uni-app的逻辑
          if (res.obj && res.obj.tubbt) {
            document.title = res.obj.tubbt
          }
          
          objlist.value = res
          
          // 完全按照uni-app的option配置
          option.value = {
            tooltip: {
              trigger: 'axis',
              axisPointer: {
                type: 'shadow'
              },
              formatter: function(params) {
                const data = params[0]
                return `${data.name}<br/>${data.seriesName}: ${data.value}${res.obj.danwei || ''}`
              }
            },
            grid: {
              left: '3%',
              right: '4%',
              bottom: '15%',
              top: '10%',
              containLabel: true
            },
            xAxis: {
              type: 'category',
              data: res.obj.lbt_shuzu || [],
              axisLabel: {
                rotate: 45, // 让底部日期斜着45度展示
                fontSize: 12,
                color: '#666'
              },
              axisTick: {
                show: false
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#e6e6e6'
                }
              }
            },
            yAxis: {
              type: 'value',
              axisLabel: {
                formatter: (val) => {
                  return val + (res.obj.danwei || '')
                },
                fontSize: 12,
                color: '#666'
              },
              splitLine: {
                show: true,
                lineStyle: {
                  color: '#f0f0f0',
                  type: 'dashed'
                }
              },
              axisLine: {
                show: false
              },
              axisTick: {
                show: false
              }
            },
            legend: {
              show: true,
              top: '88%',
              left: 'center',
              textStyle: {
                fontSize: 12,
                color: '#333'
              }
            },
            series: [{
              name: res.obj.liebt || '数据',
              data: res.obj.zhi_shuzu || [],
              type: 'bar',
              color: '#7491e9',
              barWidth: 12,
              barMaxWidth: 15,
              label: {
                show: true,
                position: 'top',
                fontSize: 10,
                color: '#333',
                formatter: function(params) {
                  return params.value === 0 ? '' : params.value
                }
              },
              itemStyle: {
                borderRadius: [2, 2, 0, 0] // 顶部圆角
              }
            }]
          }
          
          console.log('uniapp风格 图表配置:', option.value)
          
          // 渲染图表 - 确保DOM更新后再渲染
          nextTick(() => {
            setTimeout(() => {
              renderChart()
            }, 100) // 延迟一点确保DOM完全渲染
          })
        } else {
          console.log('uniapp风格 API返回错误:', res)
          // 设置错误状态，但仍显示界面
          objlist.value = {
            leixing: 'error',
            obj: null
          }
        }
      } catch (error) {
        console.log('uniapp风格 获取统计数据失败:', error)
        // 设置错误状态，但仍显示界面
        objlist.value = {
          leixing: 'error',
          obj: null
        }
      } finally {
        loading.value = false
      }
    }
    
    // 渲染图表
    const renderChart = () => {
      console.log('uniapp风格 开始渲染图表')
      console.log('uniapp风格 chartRef.value:', chartRef.value)
      console.log('uniapp风格 option.value.series:', option.value.series)
      console.log('uniapp风格 图表容器尺寸:', chartheight.value, chartwidth.value)
      
      if (!chartRef.value) {
        console.log('uniapp风格 图表容器不存在')
        return
      }
      
      if (!option.value.series || !option.value.series.length) {
        console.log('uniapp风格 图表数据不存在')
        return
      }
      
      try {
        // 销毁之前的图表实例
        if (chartInstance) {
          console.log('uniapp风格 销毁之前的图表实例')
          chartInstance.dispose()
          chartInstance = null
        }
        
        // 创建新的图表实例
        console.log('uniapp风格 创建新的图表实例')
        chartInstance = echarts.init(chartRef.value)
        chartInstance.setOption(option.value, true) // 第二个参数为true表示完全替换
        
        console.log('uniapp风格 图表渲染完成')
        console.log('uniapp风格 图表数据:', option.value.series[0].data)
        console.log('uniapp风格 X轴标签:', option.value.xAxis.data)
      } catch (error) {
        console.log('uniapp风格 图表渲染失败:', error)
      }
    }
    
    // 日期变化处理 - 按照uni-app的bindDateChange方法
    const bindDateChange = (value) => {
      console.log('uniapp风格 日期变化:', value)
      date.value = value
      getData_index()
    }
    
    // 页面初始化 - 按照uni-app的onLoad逻辑
    onMounted(async () => {
      console.log('uniapp风格 统计报表页面初始化')
      console.log('uniapp风格 路由参数:', route.query)
      
      // 初始化路由参数 - 模拟uni-app的onLoad方法
      initializeFromRoute()
      
      // 更新屏幕尺寸
      updateScreenWidth()
      
      // 监听屏幕旋转/大小变化 - 统一管理resize事件
      const resizeHandler = () => {
        updateScreenWidth()
      }
      window.addEventListener('resize', resizeHandler)
      
      // 在组件卸载时移除事件监听器
      onUnmounted(() => {
        window.removeEventListener('resize', resizeHandler)
        if (chartInstance) {
          chartInstance.dispose()
          chartInstance = null
        }
      })
      
      // 立即获取数据 - 确保页面加载时就开始请求
      console.log('uniapp风格 立即开始获取数据, dtype:', dtype.value)
      getData_index()
    })
    
    // 监听objlist变化，确保数据更新后重新渲染图表
    watch(
      () => objlist.value,
      (newVal) => {
        console.log('uniapp风格 objlist数据变化:', newVal)
        if (newVal && newVal.leixing === 'ok' && newVal.obj) {
          nextTick(() => {
            setTimeout(() => {
              console.log('uniapp风格 数据变化后重新渲染图表')
              renderChart()
            }, 200)
          })
        }
      },
      { deep: true }
    )
    
    // 监听路由参数变化，重新初始化数据
    watch(
      () => route.query,
      (newQuery, oldQuery) => {
        console.log('路由参数变化:', { newQuery, oldQuery })
        // 只有当type参数发生变化时才重新加载
        if (newQuery.type !== oldQuery?.type || newQuery.dtype !== oldQuery?.dtype) {
          initializeFromRoute()
          getData_index()
        }
      },
      { deep: true }
    )
    return {
      route,
      loading,
      chartRef,
      objlist,
      option,
      dtype,
      date,
      chartheight,
      chartwidth,
      initializeFromRoute,
      getData_index,
      bindDateChange,
      Search
    }
  }
}
</script>

<style scoped lang="scss">
/* 完全按照uni-app的样式 */
.searchB_hp {
  min-width: 160px;
  height: 30px;
  background-color: #ffffff;
  border-radius: 10px;
  z-index: 1000;
  text-align: left;
  padding: 0 5px;
  margin: 10px;
  font-size: 18px;
  display: flex;
  align-items: center;
  border: 2px solid #0db172;
  line-height: 30px;
  
  .search-icon {
    width: 20px;
    height: 20px;
    margin-right: 10px;
    color: #0db172;
  }
  
  .date-picker {
    flex: 1;
    border: none;
    background: transparent;
    
    :deep(.el-input__wrapper) {
      background: transparent;
      box-shadow: none;
      padding: 0;
    }
    
    :deep(.el-input__inner) {
      font-size: 14px;
      color: #333;
    }
  }
}

.content {
  display: flex;
  flex-direction: column;
  height: 100vh;
  width: 100vw;
  overflow-x: auto;
  overflow-y: auto;
  background: #f5f5f5;
}

.echatu {
  flex: 1;
  padding: 10px;
  overflow: hidden;
}

.loading-wrapper {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 400px;
}

.loading-state {
  background: #f5f5f5;
}

.empty-state {
  background: #f5f5f5;
}


</style>
